package org.paradigmshift.cumulusfracto.filesystem;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.alfresco.jlan.server.auth.ClientInfo;
import org.alfresco.jlan.server.filesys.AccessDeniedException;
import org.alfresco.jlan.server.filesys.DiskOfflineException;
import org.paradigmshift.cumulusfracto.core.CumulusFracto;
import com.google.gdata.client.GoogleService.CaptchaRequiredException;
import com.google.gdata.client.GoogleService.ServiceUnavailableException;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ResourceNotFoundException;
import com.google.gdata.util.ServiceException;


public class CumulusFractoClientInfo extends ClientInfo {
	
	private DocsService docsService = new DocsService( CumulusFracto.APP_NAME );
	private String authToken;
	
	private URL allContents;
	private URL rootContents;
	
	protected CumulusFractoClientInfo( String user, byte[] pwd ) {

		super( user, pwd );
		
		try {
			
			allContents = new URL( "http://docs.google.com/feeds/default/private/full" );
			rootContents = new URL( "http://docs.google.com/feeds/default/private/full/folder%3Aroot/contents");
		}
		catch ( MalformedURLException murle ) {}
	}
	
	public DocsService getDocsService() {
		
		return docsService;
	}
	
	public String getAuthToken() {
		
		return authToken;
	}
	
	public void setAuthToken( String authToken ) {
		
		this.authToken = authToken;
	}
	
	public URL getAllContentsURL() {
		
		return this.allContents;
	}
	
	public URL getRootContentsURL() {
		
		return this.rootContents;
	}
	
	public DocumentListFeed getAllContentsFeed() throws IOException {
		
		return getFeed( this.allContents );
	}
	
	public DocumentListFeed getRootContentsFeed() throws IOException {
		
		return getFeed( this.rootContents );
	}
	
	private DocumentListFeed getFeed( URL url ) throws IOException {
		
		try {
			
			return docsService.getFeed( url, DocumentListFeed.class );
		}
		catch ( CaptchaRequiredException cre ) {
			
			// TODO: send user to the captcha web page
			throw new AccessDeniedException( "Captcha required." );
		}
		catch ( ServiceUnavailableException sue ) {
			
			throw new DiskOfflineException( "Google Docs unavailable." );
		}
		catch ( AuthenticationException ae ) {
			
			throw new AccessDeniedException( "Access denied." );
		}
		catch ( ResourceNotFoundException rnfe ) {
			
			throw new FileNotFoundException( "Resource not found. " );
		}
		catch ( ServiceException se ) {
			
			throw new IOException( se );
		}
	}
}
